$(function() {

	$( "#customername" ).autocomplete({
		source: "?mod=customer&act=autocomplete&xvtrs=none",
		minLength: 2,
		select: function( event, ui ) {
			// Load Customer Data and fill the form
			fillCustomerInfo(ui.item.id);
		}
	});
});

/**
 * Fill the Customer Information block in the inquiry creation/update screen
 * @param customerid	Id of the selected customer
 */
function fillCustomerInfo(customerid)
{
	tgurl = '?mod=customer&act=info&xvtrs=none';
	sdata = '&customerid='+customerid;
	var successFunction = function(data) 
	{
		try{
			var json = JSON.parse(data);
			$("#customerid").val(customerid);
			$("#street").val(json.street);
			$("#postal_code").val(json.postal_code);
			$("#phone1").val(json.phone1);
			$("#email1").val(json.email1);
			$("#function").val(json.functionValue);
			$("#city").val(json.city);
			$("#contactid").val('');
			
		}
		catch (e) 
		{
			
		}
		
		$( "#contact" ).autocomplete({
			source: "?mod=customer&act=partners&sac=autocomplete&xvtrs=none&customerid="+customerid,
			minLength: 1,
			select: function( event, ui ) {
				// Load Customer Data and fill the form
				fillContactInfo(ui.item.id);
			}
		});
	};
	$.ajax({
		type: 'POST',
		url: tgurl,
		data: sdata,
		success: successFunction
	});
}

/**
 * Fill the Customer Information block in the inquiry creation/update screen
 * @param customerid	Id of the selected customer
 */
function fillContactInfo(customerid)
{
	tgurl = '?mod=customer&act=info&xvtrs=none';
	sdata = '&customerid='+customerid;
	var successFunction = function(data) 
	{
		try{
			var json = JSON.parse(data);
			$("#contactid").val(json.customerid);
			if(json.street != '' && json.street)
			{
				$("#street").val(json.street);
			}
			if(json.postal_code != '' && json.postal_code)
			{
				$("#postal_code").val(json.postal_code);
			}
			if(json.phone1 != '' && json.phone1)
			{
				$("#phone1").val(json.phone1);
			}
			if(json.email1 != '' && json.email1)
			{
				$("#email1").val(json.email1);
			}
			if(json.city != '' && json.city )
			{
				$("#city").val(json.city);
			}
			if(json.functionValue != '' && json.functionValue)
			{
				$("#function").val(json.functionValue);
			}
		}
		catch (e) 
		{
			
		}
	};
	$.ajax({
		type: 'POST',
		url: tgurl,
		data: sdata,
		success: successFunction
	});
}